<template>
  <div>
    <my-head title="重置密码"> </my-head>
    <van-form class="form" ref="form" @submit="onSubmit" @failed="onFailed">
      <PassInput
        v-model="form.oldpass"
        name="oldpass"
        label="旧密码"
        placeholder="旧密码"
        @blur="checkNewPass"
      ></PassInput>
      <PassInput
        v-model="form.newpass"
        name="newpass"
        label="新密码"
        placeholder="新密码"
        @blur="checkPassword"
        :rules="[{ validator: comparePass, message: '新旧密码不能相等' }]"
      ></PassInput>
      <PassInput
        v-model="form.dbnewpass"
        name="dbnewpass"
        label="确认新密码"
        placeholder="确认新密码"
        :rules="[{ validator: checkTwoPass, message: '两次密码不匹配' }]"
      ></PassInput>
      <div style="margin: 16px" class="mt10">
        <van-button round block type="info" native-type="submit"
          >确认修改</van-button
        >
      </div>
      <div style="margin: 16px">
        <van-button round block type="danger" native-type="reset"
          >重置</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { tochangeuserinfo } from "@/api/api";
export default {
  data() {
    return {
      form: {},
    };
  },
  mounted() {
    console.log(this.userInfo);
  },
  methods: {
    checkNewPass() {
      if (
        this.reg.pwd.test(this.form.oldpass) &&
        this.reg.pwd.test(this.form.newpass)
      ) {
        this.$refs.form.validate("newpass").catch((err) => {});
      }
    },
    comparePass(val) {
      // 比较新密码和旧密码
      if (this.reg.pwd.test(val) && this.reg.pwd.test(this.form.oldpass)) {
        return val !== this.form.oldpass;
      }
    },
    checkPassword() {
      if (
        this.reg.pwd.test(this.form.newpass) &&
        this.reg.pwd.test(this.form.dbnewpass)
      ) {
        this.$refs.form.validate("dbnewpass").catch((err) => {});
      }
    },
    checkTwoPass(val) {
      if (this.reg.pwd.test(val) && this.reg.pwd.test(this.form.newpass)) {
        return val == this.form.newpass;
      } else {
        return false;
      }
    },
    async onSubmit(val) {
      console.log(val);
      if (val.oldpass !== this.userInfo.password) {
        this.ShowToast("旧密码不正确");
      } else {
        let res = await tochangeuserinfo({
          password: val.newpass,
        });
        if (res.code == 200) {
          this.ShowSuccess("修改密码成功");
          sessionStorage.removeItem("token");
          this.getUesrInfoData(null);
          this.gotopage("/login");
        }
      }
    },
    onFailed() {
      this.ShowError("密码校验失败");
    },
  },
};
</script>

<style>
.form {
  padding: 30px 10px;
}
</style>

